<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix" v-if="this.$route.query.id">
        <span>模拟流程：{{ $route.query.name }}</span>
        <el-button
          style="float: right; padding: 3px 0; margin-right: 10px"
          type="text"
          @click="$router.push({ path: '/workflow/list' })"
          >返回</el-button
        >
      </div>
      <div>
        <div>
          <el-input
            v-show="!hasControls"
            type="textarea"
            :rows="5"
            placeholder="表单json数据(key 和字符一定要双引号)"
            v-model="workTaskForm.formData"
          ></el-input>
          <controlPanel
            v-show="hasControls"
            ref="controlPanel"
            :isEdit="true"
          ></controlPanel>
        </div>
        <br />
        <el-form :inline="true" class="demo-form-inline">
          <!-- <el-form-item label="">
            <el-select
              placeholder="发起人"
              size="mini"
              v-model="workTaskForm.createdUserId"
            >
              <el-option
                v-for="item in allUsers"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-checkbox v-model="isSimulation">是否模拟</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="startWork"
              >发起流程</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 10px">
      <div slot="header" class="clearfix">
        <span>流程实例</span>
      </div>
      <el-table
        ref="singleTable"
        v-loading="loading"
        :data="[workTaskForm]"
        highlight-current-row
      >
        <!-- <el-table-column type="selection" width="50"> </el-table-column> -->
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column property="name" label="流程名称" width="200">
        </el-table-column>
        <el-table-column property="formData" label="表单"> </el-table-column>
        <el-table-column property="workTaskStatus" label="状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.workTaskStatus == 0">待发起</span>
            <span v-if="scope.row.workTaskStatus == 1">审批中</span>
            <span v-if="scope.row.workTaskStatus == 2">已审批</span>
          </template>
        </el-table-column>
        <el-table-column
          property="createdUserId"
          label="创建用户id"
          width="200"
        >
          <template slot-scope="scope">
            <span>{{ getUserName(scope.row.createdUserId) }}</span>
          </template>
        </el-table-column>
        <el-table-column property="creationTime" label="创建时间" width="320">
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 审批 -->

    <processForm ref="processForm"></processForm>
  </div>
</template>

<script>
import nodeUser from "./nodeUser";
import processForm from "./processForm";
import controlPanel from "@/views/workflows/formDesign/controlPanel.vue";
import defaultToVfrom from '@/views/workflows/formDesign/designContentConverters/defaultToVfrom'
export default {
  components: { nodeUser, processForm, controlPanel },
  name: "workflow-simulation",
  props: {
    workflowName: {
      default: "测试流程",
    },
    workflowId: {
      default: "1",
    },
    workflowVersionNo: {
      default: "1",
    },
  },
  computed: {
    id() {
      return this.$route.query.id || this.workflowId;
    },
    name() {
      return this.$route.query.name || this.workflowName;
    },
    versionNo() {
      return this.$route.query.versionNo || this.workflowVersionNo;
    },
    canHandle() {
      return (
        this.workHistories.filter(
          (w) =>
            w.handleUser.id == this.$store.state.user.user.id &&
            w.isHandled == 0 &&
            w.workStepType == 0
        ).length > 0
      );
    },
    currentUserId() {
      return this.$store.state.user.user.id;
    },
  },
  watch: {
    "workTaskForm.createdUserId": {
      handler() {
        //保存当前用户到cookie

        var user = this.allUsers.filter(
          (u) => u.id == this.workTaskForm.createdUserId
        )[0];
        user.isManager = true;
        this.$store.dispatch("user/setCurrentUser", user);
      },
    },
    isPass: {
      handler() {
        if (this.isPass) this.workStep.rejectToNodeId = null;
        else this.getRejectNodes(); // 载入驳回节点
      },
    },
  },
  data() {
    return {
      formData: "",
      loading: false,
      allUsers: [],
      workTaskForm: {
        id: "",
        createdUserId: "",
        entityFullName: "",
        entityKeyValue: "",
        formData: "{}",
        workTaskStatus: "",
        name: "模拟流程",
        workflowId: {},
      },
      workStep: {
        handleUser: {
          id: "",
        },
        userSelectors: [
          {
            selectorId: "",
            selectorName: "",
            selections: [],
            parameter: "",
            description: "",
            handleType: 0,
          },
        ],
        rejectNodes: [
          {
            id: "",
            name: "",
          },
        ],
        comment: "",
        stepId: "",
        formData: "",
        rejectToNodeId: null,
      },
      workHistories: [],
      isForward: false,
      isPass: true,
      isSimulation: true,
      hasControls: false,
      //用于动态查询审批人
      workflowInfo: {
        workflowId: "",
        versionNo: "",
        FormData: "",
      },
      timeoutTask:0
    };
  },
  mounted() {
    this.getAllUserForSimulation();
    this.getFormDesignVersionByWorkflowId({
      id: this.id,
      version: this.versionNo,
    });
    this.watchForecastNodeUsers();
  },
  methods: {
    goback() {
      this.$navtab.close(this.$route.fullPath);
    },
    getAllUserForSimulation() {
      // this.$store.dispatch("user/getAllList").then((res) => {
      this.$store.dispatch("workflow/GetAllUserForSimulation").then((res) => {
        this.allUsers = res;
        this.workTaskForm.createdUserId = this.allUsers[0].id;
      });
    },

    getUserName(userId) {
      var users = this.allUsers.filter((u) => u.id == userId);
      return users.length > 0 ? users[0].name : "";
    },
    startWork() {
      this.loading = true;
      this.workTaskForm.workflowId = {
        versionNo: Number(this.versionNo),
        id: this.id,
      };
      this.workTaskForm.entityFullName = "Simulation";
      this.workTaskForm.entityKeyValue = new Date().getTime().toString();
      if (this.hasControls) {
        this.workTaskForm.formData = JSON.stringify(
          this.$refs.controlPanel.getValue()
        );
      }

      this.workTaskForm.createdUserId = this.currentUserId;

      let _this = this;
      console.log("this.isSimulation", this.isSimulation);
      let dispatchPath = this.isSimulation
        ? "workflow/createSimulationWorkTask"
        : "workflow/createWorkTask";
      this.$store
        .dispatch(dispatchPath, this.workTaskForm)
        .then((res) => {
          this.workTaskForm = res;
          return res;
        })
        .then((task) => {
          const data = {
            workTaskId: task.id,
          };
          this.$store
            .dispatch("workflow/startWorkTask", data)
            .then((res) => {
              _this.loading = false;
              this.$refs.processForm.loadHistories(this.workTaskForm);
            })
            .catch((e) => {
              this.loading = false;
            });
        })
        .catch((e) => {
          this.loading = false;
        });
    },
    getFormDesignVersionByWorkflowId(formDesignId) {
      this.loading = true;
      this.$store
        .dispatch(
          "dynamicFormDesign/getFormDesignVersionByWorkflowId",
          formDesignId
        )
        .then((res) => {
          this.loading = false;
          this.formDesign = res;
          if (res && res.designContent) {
            if (res.designFramework != "vform") {
              return defaultToVfrom(res.designContent);
            } else {
              return JSON.parse(res.designContent || "{}");
            }
          } else return null;
        })
        .then((controls) => {
          this.loading = false;
          if (controls && controls.widgetList && controls.widgetList.length> 0) {
            this.hasControls = true;
            this.$refs.controlPanel.setValue(controls, {});
          } else {
            this.workTaskForm.formData = JSON.stringify({ sample: 20 });
          }
        });
    },
    watchForecastNodeUsers() {
      let _this = this;
      this.workTaskForm.workflowId = {
        versionNo: Number(this.versionNo),
        id: this.id,
      };
      clearTimeout(this.timeoutTask)
      this.timeoutTask = setTimeout(() => {
        let formData = _this.workTaskForm.formData;
        if (_this.hasControls && _this.$refs.controlPanel)
          formData = JSON.stringify(_this.$refs.controlPanel.getValue());
        if (_this.$refs.processForm) {
          _this.$refs.processForm.getForecastNodeUsers4Workflow({
            formData: formData,
            workflowId: _this.workTaskForm.workflowId.id,
            versionNo: _this.workTaskForm.workflowId.versionNo,
          });
        }

        _this.watchForecastNodeUsers();
      }, 600);
    },
  },
};
</script>

<style></style>
